from playwright.sync_api import expect, Page
import os
import time
from utils.tools import get_path


def page_login_save_cookies(page: Page, username: str, password: str):
    """
    通过页面进行登录
    :param page: page对象
    :param username:
    :param password:
    :return:
    """
    if os.path.exists(get_path(f"/.auth/{username}.txt")) and int(time.time() - os.path.getctime(get_path(f"/.auth/{username}.txt"))) < 86400:
        page.context.clear_cookies()
        with open(get_path(f"/.auth/{username}.txt")) as f:
            cookies = f.read()
        cookies = eval(cookies)
        page.context.add_cookies(cookies)
        page.goto("https://0123456789.pingcode.com")
        expect(page.locator('.avatar-default').first).to_be_visible()
    else:
        page.context.clear_cookies()
        page.goto("https://0123456789.pingcode.com")
        page.get_by_placeholder("请输入手机号/邮箱").type(username, delay=30)
        page.get_by_placeholder("请输入登录密码").fill(password)
        page.get_by_role("button", name="登录")
        page.get_by_role("button", name="登录").click()
        expect(page.locator('.avatar-default').first).to_be_visible()
        cookies = page.context.cookies()
        with open(get_path(f"/.auth/{username}.txt"), "w") as f:
            f.write(str(cookies))


def 跳转(page: Page, path: str):
    if path[0] != "/":
        path = f"/{path}"
    page.goto(f'{page.url.split(".com")[0]}.com{path}')
